import {
  getProductsComment,
  addCart,
  addOrder,
  addOrderProducts
} from "../../../api/path/index.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    top: 0,
    show: false,
    goodsAvg: 0,
    skuShow: false,
    sku: [
      {
        title: "颜色",
        list: ["海湾蓝", "雅灰", "橄榄绿", "珍珠白", "钻石黑", "流星蓝", "霞光紫", "熔岩橙", "寒武岩灰"],
      },
      {
        title: "内饰",
        list: ["银河灰", "曜石黑", "暮光红", "迷雾紫"],
      },
      {
        title: "版本",
        list: ["SU7", "SU7 Pro", "SU7 Max", "创始版"],
      },
    ],
    commentList: [
      {
        id: 1,
        userName: '你的晚餐',
        userImage: 'https://xckf-bucket.oss-cn-guangzhou.aliyuncs.com/102/images/cart/shangping_1.png',
        coutenr: "商品很好，真不愧是雷子！商品很好，真不愧是雷子！商品很好，真不愧是雷子！商品很好，真不愧是雷子！商品很好，真不愧是雷子！商品很好，真不愧是雷子！",
        value: 4,
      },
      {
        id: 2,
        userName: '我的傻呗',
        userImage: 'https://xckf-bucket.oss-cn-guangzhou.aliyuncs.com/102/images/cart/shangping_1.png',
        coutenr: "30w我的评价是不如凯子",
        value: 2,
      },
    ],
    selectedSku: [],
    goodsDetails: {},

  },
  openCart: function (e) {
    if (!wx.getStorageSync('token')) {
      return wx.showToast({
        title: '请先登录！',
        icon: 'error'
      })
    }

    let user = JSON.parse(wx.getStorageSync('userinfo')).userID

    addCart({
      userID: user,
      productID: this.data.goodsDetails.productID,
    }).then(res => {
      console.log(res);
      if (res.code == 1) {
        wx.showToast({
          title: res.data,
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: res.data,
          icon: 'error'
        })
      }
    })
  },
  closeCart: function (e) {
    this.setData({
      skuShow: false
    })
  },
  selectSku: function (e) {
    const { index, text } = e.currentTarget.dataset;
    let selectedSku = this.data.selectedSku;
    selectedSku[index] = text;
    this.setData({
      selectedSku: selectedSku
    })
  },
  back: function (e) {
    wx.navigateBack({
      delta: 1
    })
  },

  submit: function (e) {
    if (!wx.getStorageSync('token')) {
      return wx.showToast({
        title: '请先登录！',
        icon: 'error'
      })
    }
    let user = JSON.parse(wx.getStorageSync('userinfo'))
    addOrder({
      "userID": user.userID,
      "userName": user.username,
      "totalAmount": this.data.goodsDetails.productPrice,
      "orderStatus": "待付款",
      "shippingAddress": "这是地址",
      "paymentMethod": "微信",
      "ordersChannel": "微信",
      "consigneeAddressInfo": "这是备注"
    }).then(res => {
      console.log(res);

      if (res.code == 1) {
        wx.showToast({
          title: "创建订单成功！",
          icon: 'success'
        })
        let arr = []
        arr.push(this.data.goodsDetails.productID)
        addOrderProducts({
          "orderID": res.data,
          "productID": arr,
          "quantity": 1
        }).then(result => {
          if (result.code == 1) {
            wx.showToast({
              title: '加载中',
              icon: 'loading',
              duration: 1000
            })
            wx.setStorageSync('orderID', res.data)
            setTimeout(() => {
              wx.navigateTo({
                url: '/pagesA/pages/orderDetails/index'
              })
            }, 1000)
          }
        })
      } else {
        wx.showToast({
          title: res.data,
          icon: 'error'
        })
      }
    })
    // 判断 selectedSku 是否为空 并且 长度是否和sku 这个数组的一样
    // if (this.data.selectedSku.length == this.data.sku.length && this.data.selectedSku.length != 0) {
    //   // 加载1秒跳转
    //   wx.showToast({
    //     title: '加载中',
    //     icon: 'loading',
    //     duration: 1000
    //   })
    //   setTimeout(() => {
    //     wx.navigateTo({
    //       url: '/pagesA/pages/orderDetails/index'
    //     })
    //     // 关闭购物车
    //   }, 1000)
    // } else {
    //   this.openCart()
    // }
  },
  getProductsCommentList: function (e) {
    let avg = 0
    getProductsComment({ id: this.data.goodsDetails.productID }).then(res => {
      console.log(res);
      this.setData({
        commentList: res.data
      })
      res.data.forEach((item, index) => {
        avg += item.rating
      })
      console.log(avg);
      this.setData({
        goodsAvg: avg / res.data.length
      })
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      goodsDetails: wx.getStorageSync('goodsDetails')
    })
    // 让 selectedSku 获取sku 里面的list的第一个
    this.data.sku.forEach((item, index) => {
      this.data.selectedSku[index] = item.list[0]
      // 把 selectedSku 赋值给 data 中的 selectedSku
      this.setData({
        selectedSku: this.data.selectedSku
      })
    })
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          top: res.safeArea.top
        })
      }
    })
    this.getProductsCommentList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 卸载mobx
    this.storeBindings.destroyStoreBindings()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})